package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.MyContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    /**
     * 用户下单功能实现
     *
     * @param orders
     */
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void addWithOrderDetail(Orders orders) {
        //想下单需要先去查询一下购物车是否为空

        Long useId = MyContext.getLoginId();
        LambdaQueryWrapper<ShoppingCart> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId, useId);

        //查询出来购物车里面全部菜品及套餐信息
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw1);
        if (shoppingCartList.size() == 0 || shoppingCartList == null) {
            throw new CustomException("购物车为空,不能下单");
        }

        //添加订单表(订单生成了才有id,订单明细才能进行添加)
//手动生成只需要遍历一次购物车即可
        Long orderId = IdWorker.getId();
        orders.setId(orderId);
        //订单号(用雪花算法生成)

        orders.setNumber("RGOD" + orderId);
        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);

        //下单用户id
        orders.setUserId(useId);

        //下单时间
        orders.setOrderTime(LocalDateTime.now());

        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());

        //用户名
        User user = userMapper.selectById(useId);
        orders.setUserName(user.getName());

        //手机号(收货人的手机号)

        //  private String phone;

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("该地址已失效");
        }
        String phone = addressBook.getPhone();
        orders.setPhone(phone);
        //地址
        orders.setAddress(addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());

        //实收金额
        AtomicInteger amount = new AtomicInteger(0);


        //添加明细表(从购物车里面直接copy)
        List<OrderDetail> orderDetailList = new ArrayList<>();

        //添加明细并计算付款金额
        for (ShoppingCart shoppingCart : shoppingCartList) {

            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, detail);
            detail.setId(null);
            detail.setOrderId(orders.getId());
            //添加到明细集合里
            orderDetailList.add(detail);
            //计算金额
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());

        }

        //保存订单表
        orders.setAmount(new BigDecimal(amount.get()));
        this.save(orders);

        //添加数据到明细表
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, useId));
    }

    /**
     * 分页订单
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Orders> pageOrders(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw1 = new LambdaQueryWrapper<>();
        lqw1.like(StringUtils.isNotBlank(number), Orders::getNumber, number)
                .between(StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)
                        ,Orders::getCheckoutTime,beginTime,endTime)
                .orderByDesc(Orders::getCheckoutTime);


        this.page(ordersPage, lqw1);
        return ordersPage;
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> userOrderPage(Integer page, Integer pageSize) {
        Long userId = MyContext.getLoginId();
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Orders::getUserId, userId).orderByDesc(Orders::getOrderTime)
                .orderByDesc(Orders::getCheckoutTime);
        this.page(ordersPage, lqw1);

        //获取该用户的订单信息
        List<Orders> orders = ordersPage.getRecords();

        List<Long> orderIds = new ArrayList<>();
        //获取订单id到明细表查询相关信息
        for (Orders order : orders) {
            //将该用户的全部订单id传入订单集合中
            orderIds.add(order.getId());

        }
        //返回订单及其明细
        Page<OrdersDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,dtoPage);
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        dtoPage.setRecords(ordersDtoList);
        //如果用户没有订单,则返回空
        if (orders == null || orders.size() == 0){
            return dtoPage;
        }
        LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(OrderDetail::getOrderId,orderIds);
        //获取用户的全部订单的订单详情(根据订单id进行匹配)
        List<OrderDetail> orderDetails = orderDetailService.list(lqw2);
        //遍历订单集合
        for (Orders order : orders) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);
            List<OrderDetail> orderDetailList = new ArrayList<>();
            //一个订单对象对应一个订单详情集合
            ordersDto.setOrderDetails(orderDetailList);

            Integer sumNum = 0;
            //遍历订单详情集合
            for (OrderDetail orderDetail : orderDetails) {
                if (order.getId().equals(orderDetail.getOrderId())){
                    //匹配成功则将订单详情添加到ordersDto
                    ordersDto.getOrderDetails().add(orderDetail);
                    sumNum += orderDetail.getNumber();
                }
            }
            ordersDto.setSumNum(sumNum);
            ordersDtoList.add(ordersDto);

        }

        return dtoPage;
    }


}
